﻿using Cms.Application.Admin.Views;
using Cms.Application.IO;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.Admin.Presenters
{
    public class StylesheetsPresenter : BasePresenter
    {
        private readonly Administrator _administrator;
        private readonly IStylesheetsView _view;
        public IDiskAccess DiskAccess;

        public StylesheetsPresenter(IStylesheetsView view)
            : this(view, new RepositoryFactory())
        {
            DiskAccess = new DiskAccess();
        }

        public StylesheetsPresenter(IStylesheetsView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            if (!_administrator.HasPermission.Stylesheets)
                _view.RedirectToPermissionDeniedPage();
        }
        
        public void Initialize()
        {
            SetStylesheets();
        }
        
        public void SetStylesheets()
        {
            _view.SetStylesheets(_administrator.CurrentSite.Stylesheets);
        }

        public void DeleteStylesheet(int id)
        {
            Stylesheet stylesheet = SiteRepository.GetStylesheet(id);
            foreach (MasterTemplateStylesheet mts in stylesheet.AssociatedMasterTemplates)
                mts.MasterTemplate.RemoveStylesheet(stylesheet);
            stylesheet.AssociatedMasterTemplates.Clear();
            stylesheet.Site.Stylesheets.Remove(stylesheet);
            stylesheet.Site = null;
            SiteRepository.SaveSite(_administrator.CurrentSite);
            DiskAccess.DeleteFile("__System\\Stylesheets\\" + id + ".css");
            SetStylesheets();
        }
    }
}